package com.dnzx.socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;

public class SocketClient {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(SocketClient.class);

	private String url;

	private int port;

	public SocketClient(String url, int port) {
		this.url = url;
		this.port = port;
	}

	public String send(byte[] req) {
		BufferedReader br = null;
		InputStream is = null;
		OutputStream os = null;
		Socket socket = null;
		String resMsg = "";
		try {
			// 1.创建客户端Socket，指定服务器地址和端口
			socket = new Socket();
			// socket.setKeepAlive(true);
			SocketAddress endpoint = new InetSocketAddress(url, port);
			socket.connect(endpoint);
			socket.setSoTimeout(5000);
			// 2.获取输出流，向服务器端发送信息
			os = socket.getOutputStream();// 字节输出流
			os.write(req);
			os.flush();
			socket.shutdownOutput();// 关闭输出流
			// 3.获取输入流，并读取服务器端的响应信息
			is = socket.getInputStream();
			br = new BufferedReader(new InputStreamReader(is));
			String info = null;
			while ((info = br.readLine()) != null) {
				System.out.println(info);
				info += info;
			}
			// ByteArrayOutputStream tagOut = new ByteArrayOutputStream();
			// byte[] mByte = new byte[2];
			// int readLength = is.read(mByte);
			// if (readLength != -1)
			// tagOut.write(mByte, 0, readLength);
			resMsg = info;
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 4.关闭资源
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return resMsg;
	}

}
